/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gestionmagasins_avec_patterns.model;

import java.util.ArrayList;

//Classe singleton
public class CatalogueUsagers 
{
    private final ArrayList<Usager> usagers;
    
    private CatalogueUsagers()
    {
        usagers = new ArrayList<>();
    }
    
    private static class CatalogueHolder//Holder pour un singleton thread safe 
    {
        static final CatalogueUsagers INSTANCE = new CatalogueUsagers();
    }
    
    public static CatalogueUsagers getInstance()
    {
        return CatalogueHolder.INSTANCE;
    }

    public void add(Usager usager) 
    {
        if(usager == null)
            throw new IllegalArgumentException("Parameter usager must not be null!");
                    
        this.usagers.add(usager);
    }

    public Usager get(int i) 
    {
        return this.usagers.get(i);
    }
    
    public ArrayList<Usager> getActivated() 
    {
        ArrayList<Usager> activatedUsers = new ArrayList<>();
        
        for(Usager u : usagers)
        {
            if(u.isActivated())
                activatedUsers.add(u);
        }
        
        return activatedUsers;
    }
        
    public ArrayList<Usager> getAll() 
    {
        return this.usagers;
    }
    
    public Usager findActivated(String username, String password) 
    {
        for(Usager u : usagers)
        {
            if(u.getUsername().equals(username) && u.getPassword().equals(password) && u.isActivated())
                return u;
        }
        
        return null;
    }
    
        public ArrayList<Usager> find(String criteria) 
    {
        ArrayList<Usager> resultList = new ArrayList<>();
        
        for(Usager u : this.usagers)
        {
            if(u.matches(criteria))
                resultList.add(u);
        }
        
        return resultList;
    }

    public boolean delete(Usager user)//retourn true si l'élément a été supprimé de la liste 
    {
        if(userHasSales(user))
        {
            user.setActivated(false);
            return false;
        }
        else
        {
            return usagers.remove(user);
        }
    }
    
    public boolean userHasSales(Usager user)
    {
        for(Vente v : CatalogueVente.getCatalogueVente().getVentes())
        {
            if(v.getVendeur().equals(user))
                return true;
        }
        
        return false;
    }

    public boolean usernameAlreadyExistsExcludeUser(String username, Usager user) 
    {
        for(Usager u : this.usagers)
        {
            if(u.getUsername().equalsIgnoreCase(username) && !u.equals(user))
                return true;
        }
        
        return false;
    }
}
